package com.kld.data.scheduler;

import com.kld.data.domain.po.SysTrans;
import com.kld.data.service.ISysTransService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;


@Configuration
public class TransDataScheduler {
    //private final ThreadPoolTaskScheduler taskScheduler;

    @Autowired(required = false)
    @Lazy
    private ISysTransService sysTranService;


    private static final Logger LOG = LoggerFactory.getLogger(TransDataScheduler.class);

    /**
     * 线程池容量
     */
    private static final int THREAD_POOL_SIZE = 20;

    /**
     * 线程名称前缀
     */
    private static final String THREAD_NAME_PREFIX = "trans-data-";

    /**
     * 定时任务集合，用来保存trans与定时任务的映射关系
     */
    public static Map<String, ScheduledFuture<?>> futureMap = new ConcurrentHashMap<String, ScheduledFuture<?>>();



    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(THREAD_POOL_SIZE);
        scheduler.setThreadNamePrefix(THREAD_NAME_PREFIX);
        scheduler.setWaitForTasksToCompleteOnShutdown(true);
        scheduler.setRemoveOnCancelPolicy(true);
        return scheduler;
    }

    /**
     * 系统重新启动后，任务初始化
     */
    @PostConstruct
    public void init() {

        try {
            //registExecTask(taskScheduler);

        } catch (Exception e) {
            LOG.error("初始化失败", e);
        }
    }

    /**
     * 注册已有转换任务
     *
     * @param taskScheduler
     */
    public void registExecTask(ThreadPoolTaskScheduler taskScheduler) {
        /*List<SysTrans> tasklist = sysTranService.selectSysTransList(null);
        for (SysTrans sysTrans : tasklist) {
            String status = sysTrans.getTaskStatus();
            if ("1".equals(status)) {
                registTransTask(taskScheduler, sysTrans);
            }
        }*/
    }

    /**
     * 注册转换任务
     *
     * @param taskScheduler
     */
    public void registTransTask(ThreadPoolTaskScheduler taskScheduler, SysTrans sysTrans) {

        LOG.info("=======注册转换任务======开始");

        taskScheduler.schedule(() -> {

        }, triggerContext -> {
            CronTrigger trigger = new CronTrigger(sysTrans.getCronExpression());
            return trigger.nextExecutionTime(triggerContext);
        });

        Trigger trigger = new Trigger() {

            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                CronTrigger trigger = new CronTrigger(sysTrans.getCronExpression());
                return trigger.nextExecutionTime(triggerContext);
            }
        };

        Runnable transTask = new Runnable() {

            @Override
            public void run() {
                sysTranService.executeTransTask(sysTrans);
            }
        };

        ScheduledFuture<?> future = taskScheduler.schedule(transTask, trigger);
        futureMap.put(sysTrans.getId(), future);

        LOG.info("=======注册转换任务======结束");
    }
}
